#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <ctime>


int share_count = 0;// 读写者共享
pthread_rwlock_t g_rwlock = PTHREAD_RWLOCK_INITIALIZER;// 定义一把全局的读写锁

void* Writer(void* args)
{
    auto num = *(int*)args;
    while (true)
    {
        // 加锁
        pthread_rwlock_rdlock(&g_rwlock);
        // 构造一个数据
        share_count = rand() % 100 + 1;
        std::cout << "写者_" << num << "写入了：" << share_count << std::endl;
        sleep(1);
        // 解锁
        pthread_rwlock_unlock(&g_rwlock);
    }

    delete (int*)args;
    return nullptr;
}

void* Reader(void* args)
{
    auto num = *(int*)args;
    while (true)
    {
        // 加锁
        pthread_rwlock_rdlock(&g_rwlock);
        // 读取
        std::cout << "读者_" << num << "读取了：" << share_count << std::endl;
        sleep(1);
        // 解锁
        pthread_rwlock_unlock(&g_rwlock);
    }

    delete (int*)args;
    return nullptr;
}



int main()
{
    srand(time(nullptr) ^ getpid());
    // 初始化读写锁
    pthread_rwlock_init(&g_rwlock, nullptr);

    const int read = 2; // 读线程个数
    const int write = 2;// 写线程个数
    const int total = read + write; // 总个数
    pthread_t tids[total]; // 管理线程的数组

    // 创还能线程
    for(int i = 0; i < read; i++)
    {
        int* num = new int(i);
        pthread_create(tids+i, nullptr, Writer, num);
    }

    for(int i = read; i < total; i++)
    {
        int* num = new int(i);
        pthread_create(tids+i, nullptr, Reader, num);
    }

    // 等待线程
    for(int i = 0; i < total; i++)
    {
        pthread_join(tids[i], nullptr);
    }

    // 销销毁读写锁
    pthread_rwlock_destroy(&g_rwlock);

    return 0;
}

